package com.bckj.freshnow.cart.domain.cmd;

import com.bckj.freshnow.cart.entity.Cart;
import com.bckj.freshnow.cart.entity.CartItem;
import com.bckj.freshnow.cart.model.CartItemRequest;
import com.bckj.freshnow.cart.model.CartItemResponse;
import com.bckj.freshnow.cart.repo.CartItemRepository;
import com.bckj.freshnow.cart.repo.CartRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class CartItemAddCmdExe {

    private final CartRepository cartRepository;
    private final CartItemRepository cartItemRepository;

    public CartItemResponse execute(CartItemRequest request) {
        var cart = getOrCreateCart(request.getUserId(), request.getCartType());
        request.setCartId(cart.getId());
        var cartItem = cartItemRepository.lambdaQuery()
                .eq(CartItem::getCartId, request.getCartId())
                .eq(CartItem::getGoodsId, request.getGoodsId())
                .eq(CartItem::getSkuId, request.getSkuId()).one();
        if (cartItem == null) {
            cartItem = new CartItem();
            cartItem.setCartId(request.getCartId());
            cartItem.setGoodsId(request.getGoodsId());
            cartItem.setSkuId(request.getSkuId());
            cartItem.setQuantity(request.getQuantity());
            cartItemRepository.save(cartItem);
        } else {
            cartItem.setQuantity(cartItem.getQuantity() + request.getQuantity());
            cartItemRepository.updateById(cartItem);
        }
        return new CartItemResponse();
    }

    private Cart getOrCreateCart(Long userId, Integer cartType) {
        Cart cart = cartRepository.lambdaQuery()
                .eq(Cart::getCartType, cartType)
                .eq(Cart::getUserId, userId).one();
        if (cart == null) {
            cart = new Cart();
            cart.setUserId(userId);
            cart.setCartType(cartType);
            cartRepository.save(cart);
        }
        return cart;
    }
}
